package autoteam.ui.tabs;

import java.awt.event.*;
import javax.swing.*;

import autoteam.tables.SearchTableModel;
import autoteam.ui.AutoTeamTablePanel;
import autoteam.ui.dialogs.*;

public class SearchTab extends TabPanel
{
	private static final long serialVersionUID = 1L;
	
	private final String[] list = {"Players", "Coaches", "Teams", "Leagues"};
	private final JComboBox searchType = new JComboBox(list);
	private JTextField queryBox = new JTextField(10);
	private final JButton searchButton = new JButton("Search");
	private final JButton viewButton = new JButton("View");
	private JTable table;
	private SearchTableModel searchModel;
	
	public SearchTab(JFrame owner)
	{
		super();
		setButtonActions(owner);
		searchModel = new SearchTableModel();
		
		AutoTeamTablePanel theTablePanel = new AutoTeamTablePanel(searchModel);
		theTablePanel.addComponent(searchType);
		theTablePanel.addComponent(queryBox);
		theTablePanel.addComponent(searchButton);
		theTablePanel.addComponent(viewButton);
		table = theTablePanel.getTable();
		
		this.add(theTablePanel);
	}
	
	@Override
	protected void setButtonActions(final JFrame parentFrame)
	{
		searchButton.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				searchModel.findMatches(getQueryType(), getQuery());
				searchModel.fireTableDataChanged();
			}
		});
		
		viewButton.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				if (searchModel.getQueryType().equals("Players"))
				{
					SearchPlayerDialog dialog = new SearchPlayerDialog(parentFrame,
							searchModel, table.getSelectedRow());
					dialog.setVisible(true);
				}
				else if (searchModel.getQueryType().equals("Coaches"))
				{
					SearchCoachDialog dialog = new SearchCoachDialog(parentFrame,
							searchModel, table.getSelectedRow());
					dialog.setVisible(true);
				}
				else if (searchModel.getQueryType().equals("Teams"))
				{
					SearchTeamDialog dialog = new SearchTeamDialog(parentFrame,
							searchModel, table.getSelectedRow());
					dialog.setVisible(true);
				}
				else if (searchModel.getQueryType().equals("Leagues"))
				{
					SearchLeagueDialog dialog = new SearchLeagueDialog(parentFrame,
							searchModel, table.getSelectedRow());
					dialog.setVisible(true);
				}
			}
		});
	}
	
	private String getQueryType()
	{
		return searchType.getSelectedItem().toString();
	}
	
	private String getQuery()
	{
		return queryBox.getText();
	}
}
